#include "RGame.h"
#include "ShareComponents.h"
#include "RSManager.h"
#include "Camera.h"
#include "MainGame.h"
#include "PauseScene.h"
#include "GameOver.h"
#include "MiddleScene.h"
RGame::RGame(HINSTANCE hIns, char* windowName, int w, int h) : FWGame(hIns, windowName, w, h)
{
	_current_scene=new MenuScene(this);
	D3DXMatrixIdentity(&this->matrix_transform);
}


RGame::~RGame()
{
}
void RGame::load()
{
	this->keyboard = new FWKeyboard(this);
	if (!keyboard->init()) MessageBox(NULL, "Error keyboard!", "Error!", MB_OK);
	gl_keyboard = this->keyboard;

	this->graphic = new FWGraphic(this);
	graphic->SetFontSize(D3DXVECTOR2(FONT_WIDTH,FONT_HEIGHT));
	graphic->init();
	gl_graphic = graphic;

	this->content = new FWContentManager(this);
	gl_content = content;
	RSManager::getInstance()->Init();

	_cam = new Camera(0, 215 * 32, this->Height);
	gl_camera = _cam;
	StateManager::getInstance()->addScene(_current_scene);
	_current_scene->load();
	
}
void RGame::update(float time)
{
	_current_scene=StateManager::getInstance()->getCurrentScene();
	int id_next=_current_scene->id_next_scene;
	if(id_next!=NONE_STATE)
	{
		switch(_current_scene->id_scene)
		{
			case MENU:  StateManager::getInstance()->addScene(new MiddleScene(this));	
						break;
			case MIDDEL_SCENE:
						StateManager::getInstance()->addScene(new MainGame(this));break;
			case MAINGAME:
						if(id_next==PAUSE) StateManager::getInstance()->addScene(new PauseScene(this));
						if(id_next==MENU)  
							{
								StateManager::getInstance()->returnPreScene();
								StateManager::getInstance()->returnPreScene();
						}
						if(id_next==GAMEOVER) StateManager::getInstance()->addScene(new GameOver(this));
						break;
			case PAUSE:
						StateManager::getInstance()->returnPreScene();
						if(id_next==MENU)StateManager::getInstance()->returnPreScene();

						break;
			case GAMEOVER:
						StateManager::getInstance()->returnPreScene();
						StateManager::getInstance()->returnPreScene();
						if(id_next==MENU)StateManager::getInstance()->returnPreScene();
						break;
		}
		if(! (_current_scene->id_scene==PAUSE && _current_scene->id_next_scene == MAINGAME))
			StateManager::getInstance()->getCurrentScene()->load();
		_current_scene->id_next_scene= NONE_STATE;
	}
	_current_scene=StateManager::getInstance()->getCurrentScene();
	keyboard->getState();
	if(gl_keyboard->isKeyPressed(DIK_ESCAPE) )
		this->shutdown();
	_current_scene->update(time);
	keyboard->saveState();
}
void RGame::render()
{
	graphic->clear(D3DCOLOR_XRGB(0,0,0));
	graphic->begin(_cam->getTransformedMatrix());
	_current_scene->render();
	graphic->end();
}
void RGame::shutdown()
{
	StateManager::getInstance()->clearAll();
	StateManager::getInstance()->releaseInstance();
	exit(1);
}